package com.zhanjixun.weixin.demo;

import com.google.common.collect.Lists;
import com.zhanjixun.weixin.Weixin;
import com.zhanjixun.weixin.WxMsgHandler;
import com.zhanjixun.weixin.domain.WxMsg;
import com.zhanjixun.weixin.utils.U;
import lombok.extern.log4j.Log4j;
import okio.BufferedSink;
import okio.Okio;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 斗图表情机器人
 *
 * @author :zhanjixun
 * @date : 2018/11/20 16:54
 */
@Log4j
public class DouTuLa implements WxMsgHandler {

    public static void main(String[] args) {
        Weixin weixin = Weixin.getInstance();
        weixin.login();
        weixin.setMsgHandler(new DouTuLa());
    }

    @Override
    public void handleTextMsg(WxMsg msg) {
        if (StringUtils.equals(msg.getContent(), "求图")) {
            for (String img : hotList().stream().distinct().limit(5).collect(Collectors.toSet())) {
                String imgFilePath = downloadImage(img);
                if (imgFilePath != null) {
                    Weixin.getInstance().getMessenger().sendEmoticonMsg(msg.getFromUserName(), new File(imgFilePath));
                }
                U.sleep(200);
            }
        }

    }


    @Override
    public void handleImageMsg(WxMsg msg) {

    }

    @Override
    public void handleRevokeMsg(WxMsg msg) {

    }

    @Override
    public void handleEmoticonMsg(WxMsg msg) {

    }

    @Override
    public void handleVoiceMsg(WxMsg msg) {

    }

    @Override
    public void handleVideoMsg(WxMsg msg) {

    }

    @Override
    public void handleFileMsg(WxMsg msg) {

    }

    @Override
    public void handleLinkMsg(WxMsg msg) {

    }

    @Override
    public void handleLocationMsg(WxMsg msg) {

    }

    @Override
    public void handleSysMsg(WxMsg msg) {

    }

    @Override
    public void handleCardMsg(WxMsg msg) {

    }

    @Override
    public void handleMiniProgramMsg(WxMsg msg) {

    }

    public static List<String> hotList() {
        List<String> result = Lists.newArrayList();
        for (int i = 1; i < 10; i++) {
            try {
                String url = String.format("http://www.doutula.com/photo/list/?page=%s", i);
                Document document = Jsoup.parse(new URL(url), 5000);
                Elements elements = document.select("div.random_picture img.img-responsive");
                if (elements.isEmpty()) {
                    break;
                }
                result.addAll(elements.stream().map(d -> d.attr("data-original")).collect(Collectors.toList()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Collections.shuffle(result);
        return result;
    }

    public static List<String> searchPic(String keyword) {
        List<String> result = Lists.newArrayList();
        for (int i = 1; i < 10; i++) {
            try {
                String url = String.format("http://www.doutula.com/search?type=photo&more=1&page=%s&keyword=%s", i, U.urlEncode(keyword));
                Document document = Jsoup.parse(new URL(url), 5000);
                Elements elements = document.select("div.random_picture img.img-responsive");
                if (elements.isEmpty()) {
                    break;
                }
                result.addAll(elements.stream().map(d -> d.attr("data-original")).collect(Collectors.toList()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Collections.shuffle(result);
        return result;
    }

    public static String downloadImage(String img) {
        try {
            String formatName = StringUtils.substringAfterLast(img, ".");
            String fileName = StringUtils.substringAfterLast(img, "/");
            String imgFilePath;
            if (formatName.equals("gif")) {
                File file = U.newFile("temp/" + fileName);
                imgFilePath = file.getAbsolutePath();

                BufferedSink buffer = Okio.buffer(Okio.sink(file));
                buffer.writeAll(Okio.source(new URL(img).openStream()));
                buffer.flush();
            } else {
                //图片变成gif
                fileName = fileName.replace("." + formatName, ".gif");
                imgFilePath = U.downloadImage(ImageIO.read(new URL(img)), fileName);
            }
            return imgFilePath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
